package com.zfc.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.zfc.entity.User;
import com.zfc.service.UserService;
import com.zfc.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/user/login/{name}/{pwd}")
    public Map<String, Object> login(User user){
        log.info("name: [{}]", user.getName());
        log.info("pwd:[{}]", user.getPwd());
        Map<String, Object> map = new HashMap<>();
        User userDB = userService.login(user);
        if(userDB != null){
            map.put("state", true);
            map.put("msg", "查询成功！");
            Map<String, String> playload = new HashMap<>();
            playload.put("name", userDB.getName());
            playload.put("id", userDB.getId()+"");
            String token = JWTUtil.getToken(playload);
            log.info("token: [{}]", token);
            map.put("token", token);
            return map;
        }
        map.put("state", false);
        map.put("msg", "查询失败！");
        return map;
    }

    @PostMapping("/test")
    public Map<String, Object> otherProcess(HttpServletRequest request){
        Map<String , Object> map = new HashMap<>();
        //认证成功，具体逻辑实现
        map.put("state", true);
        map.put("msg", "jwt认证成功！");
        DecodedJWT decodedJWT = JWTUtil.vertifyToken(request.getHeader("token"));
        log.info("name: [{}]", decodedJWT.getClaim("name").asString());
        log.info("id: [{}]", decodedJWT.getClaim("id").asString());
        return map;
    }

}
